package pe.com.ztaxi.taxis.util;

import java.util.ArrayList;

import org.springframework.stereotype.Component;

import pe.com.ztaxi.taxis.model.Punto;

@Component
public class PoligonoUtil {

	public boolean isPointInPolygon(Punto tap, ArrayList<Punto> vertices) {
	    int intersectCount = 0;
	    for(int j=0; j<vertices.size()-1; j++) {
	        if( rayCastIntersect(tap, vertices.get(j), vertices.get(j+1)) ) {
	            intersectCount++;
	        }
	    }

	    return (intersectCount%2) == 1; // odd = inside, even = outside;
	}

	private boolean rayCastIntersect(Punto tap, Punto vertA, Punto vertB) {

	    double aY = vertA.getLatitud();
	    double bY = vertB.getLatitud();
	    double aX = vertA.getLongitud();
	    double bX = vertB.getLongitud();
	    double pY = tap.getLatitud();
	    double pX = tap.getLongitud();

	    if ( (aY>pY && bY>pY) || (aY<pY && bY<pY) || (aX<pX && bX<pX) ) {
	        return false; // a and b can't both be above or below pt.y, and a or b must be east of pt.x
	    }

	    double m = (aY-bY) / (aX-bX);               // Rise over run
	    double bee = (-aX) * m + aY;                // y = mx + b
	    double x = (pY - bee) / m;                  // algebra is neat!

	    return x > pX;
	}
	
}
